// setAddress和getaddress是本地存储的地址信息的写入的读取方法
import { setAddress, getAddress } from "@/utils/auth";
// import {setAddress} from "@/utils/auth"

export default {
  namespaced: true,
  state: {
    // 保存地址信息
    list: [],
    info: {},
    findId: 0,
    //存储购物车传过去的商品信息
    CartsInfo:[],
  },
  mutations: {
    init(state) {
      if (getAddress() == null) {
        state.list = [];
      } else {
        state.list = getAddress();
      }
    },
    saveCart(state,payload) {
          state.CartsInfo = payload;
          console.log(state.CartsInfo);
    },
    add(state, payload) {
      //将符合条件的条件筛选出来
      let formatObj = {
        id: Date.now(),
        name: payload.name,
        tel: payload.tel,
        address: payload.addressDetail,
        isDefault: payload.isDefault ? payload.isDefault : false,
        areaCode: payload.areaCode,
        postalCode: payload.postalCode,
      };
      if (state.list != null) {
        state.list.push(formatObj);
        setAddress(state.list);
      } else {
        state.list = [];
        state.list.push(formatObj);
        setAddress(state.list);
      }
    },
    Edit(state, payload) {
      console.log(payload);
      state.findId = payload;
      state.info = state.list.find((item) => item.id == payload);
      console.log(state.info);
    },
    updata(state, payload) {
      let formatObj = {
        id: state.findId,
        name: payload.name,
        tel: payload.tel,
        address: payload.addressDetail,
        isDefault: payload.isDefault ? payload.isDefault : false,
        areaCode: payload.areaCode,
        postalCode: payload.postalCode,
      };
      console.log(state.findId);
      //  console.log(JSON.parse(JSON.stringify(formatObj)));
      console.log(formatObj);
      let index = state.list.findIndex((item) => {
        return item.id == state.findId;
      });
      console.log(index);
      // eslint-disable-next-line no-unused-vars
      state.list[index] = formatObj;
      setAddress(state.list);
    },
    delData(state) {
      let index = state.list.findIndex((item) => {
        return item.id == state.findId;
      });
      console.log(state.findId);
      state.list.splice(index, 1);
      setAddress(state.list);
    },
  },
};
